package com.woniu.park.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.woniu.park.controller.form.ParkspaceForm;
import com.woniu.park.controller.form.UserForm;
import com.woniu.park.dao.UserMapper;
import com.woniu.park.entity.*;
import com.woniu.park.service.SmsService;
import com.woniu.park.util.*;
import com.woniu.park.service.IUserRoleService;
import com.woniu.park.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxb
 * @since 2020-09-05
 */
@RestController
//@RequestMapping("/park/user")
@Slf4j
@CrossOrigin//跨域支持
public class UserController {

    private  static final String PATH="";//文件上传指定路径
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IUserRoleService iUserRoleService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private  RedisTemplate<String, String> redisTemplate;//阿里云短信模板
    @Autowired
    private UserMapper userMapper;
    /*
        注册
     */
    @PostMapping("register")
    public Result registerCode(@Valid @RequestBody UserForm userForm){
        iUserService.registerCode(userForm);
        return Result.success();

    }
    /*
           xjy
        文件上传
     */
    @PostMapping("upload")
    public Result uploading(MultipartFile avatar)throws IOException{
        System.out.println(avatar.getOriginalFilename());
        //构造文件名
        String yyyyMMddHHmmssSSS = TimeUtil.getAccurateTime();
        int random = new Random().nextInt(10);
        String filename = yyyyMMddHHmmssSSS+random+avatar.getOriginalFilename();
        String path = PATH+"\\"+filename;
        System.out.println(filename);
        System.out.println(path);
        //转存到指定路径
        avatar.transferTo(new File(path));
        return  Result.success();
    }
    /*
          xjy
          生成推荐码
       */
    @GetMapping("code")
    public Result code(){
        //通过shiro获取id
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        return  Result.success("1","生成推荐码",iUserService.code(user.getUserId()));
    }

    //查看租给了谁
    @GetMapping("checkPark")
    public Result checkPark(HttpSession session){
        //根据uid查有该用户多少个车位
        //从session中取uid  目前定死
        User userSession = (User)session.getAttribute("user");
        int userId=userSession.getUserId();
        List<Parkspace> parkspaces =iUserService.findParkById(userId);
        List<OrderInfo> orderInfos=new ArrayList<>();
        for (Parkspace parkspace : parkspaces) {
            //根据车位查询租客id定位用户姓名
            Order order= iUserService.findByParkspaceId(parkspace.getParkspaceId());
            if (order != null) {
                User user=iUserService.findByUserId(order.getOrderUserId());
                OrderInfo orderInfo=new OrderInfo();
                BeanUtils.copyProperties(user,orderInfo);
                BeanUtils.copyProperties(order,orderInfo);
                orderInfos.add(orderInfo);
            }
        }
        log.info("车位使用详情:{}",orderInfos);
        return Result.success("1","查询车位使用情况成功",orderInfos);
    }

    /**
     * 历史订单查询
     * @return
     */
    @GetMapping("historyOrder")
    public Result historyOrder(HttpSession session) {
        //根据uid查order
        User userSession = (User)session.getAttribute("user");
        int userId=userSession.getUserId();
        List<Parkspace> parkspaces =iUserService.findParkById(userId);
        List<OrderInfo> orderInfos=new ArrayList<>();
        List<Integer> parkspaceIds=new ArrayList<>();
        for (Parkspace parkspace : parkspaces) {
            parkspaceIds.add(parkspace.getParkspaceId());
        }
        List<Order> orders= iUserService.findByParkspaceIdNotStatus(parkspaceIds);
        for (Order order : orders) {
            if (order != null) {
                //根据车位查询租客id定位用户姓名
                User user=iUserService.findByUserId(order.getOrderUserId());
                OrderInfo orderInfo=new OrderInfo();
                BeanUtils.copyProperties(user,orderInfo);
                BeanUtils.copyProperties(order,orderInfo);
                orderInfos.add(orderInfo);
            }
        }
        log.info("历史订单详情:{}",orderInfos);
        return Result.success("1","查询历史订单成功",orderInfos);
    }

    /*
        用户登录（密码登录/短信登录）
     */
    @PostMapping("login")
    public Result userLogin(@RequestBody UserForm userForm,HttpSession session) {
        String tel= userForm.getUserTel();
        log.info("登录操作:{}",tel);
        String code = userForm.getCode();
        Subject currUser = SecurityUtils.getSubject();
        //①用短信登录短信时
        if(!StringUtils.isEmpty(code)){
            //短信登录和user_message_status修改为1
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.set("user_message_status",1).eq("user_tel",tel);
            userMapper.update(null,wrapper);
            String sessionCode = (String)session.getAttribute("code");
            System.out.println(sessionCode);
                //短信验证码验证
            if (StringUtils.isEmpty(sessionCode)){
                return Result.fail("80003","请先获取短信");
            }
            if (sessionCode.equals(code)){
                log.info("阿里云获取验证码：{}，用户输入验证码：{}",sessionCode,code);
                currUser.login(new UsernamePasswordToken(tel,code));
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("user_tel",tel);
                User user = iUserService.getOne(userQueryWrapper);
                session.setAttribute("userId",user.getUserId());
                session.setAttribute("user",user);
                return Result.success("1","登录成功");
            }else{
                return  Result.fail("80006","验证码错误");
            }
            //return Result.fail("30000","短信输入不能为空");
        }else{
            //短信登录和user_message_status修改为1
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.set("user_message_status",2).eq("user_tel",tel);
            userMapper.update(null,wrapper);
            //②密码账号登录
            try {
                String password = userForm.getUserPassword();
                currUser.login(new UsernamePasswordToken(tel,password));
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("user_tel",tel);
                User user = iUserService.getOne(userQueryWrapper);
                session.setAttribute("user",user);
                return Result.success("1","登录成功");
            } catch (AuthenticationException e) {
                log.info("登录失败", e);
                return Result.fail("AUTH_ERROR", "用户名或者密码错误");
            }
        }
    }

    /*
        修改密码
     */
    @PostMapping("change")
    public Result changePassword(@RequestBody UserForm userForm ,HttpSession session){
        String password = userForm.getUserPassword();
        String confirmPassword = userForm.getConfirmPassword();
        if(StringUtils.isEmpty(password) || StringUtils.isEmpty(confirmPassword)){
            return Result.fail("30000","密码输入不能为空");
        }
        final Object sessionCaptcha = session.getAttribute("captcha");
        if(sessionCaptcha==null){
            return Result.fail("20017","请您先获取验证码");
        }
        if(!sessionCaptcha.equals(userForm.getCaptcha())){
            return Result.fail("20007","您输入的验证码不正确");
        }
        if(confirmPassword.equals(password)){
            iUserService.changePassword(userForm.getUserId(),confirmPassword);
        }else{
            return Result.fail("200031","两次密码输入不一致");
        }
        iUserService.changePassword(userForm.getUserId(),confirmPassword);
        return Result.success("1","密码修改成功");
    }

    /*获取当前登录的用户电话
     *
     */
    @GetMapping("/user")
    public Result tel(HttpSession session){
        //从session中取uid  目前定死
        User user = (User)session.getAttribute("user");
//        int userId=userSession.getUserId();
//        User user = (User)SecurityUtils.getSubject().getPrincipal();
        if(user!=null){
            return Result.success("1","用户信息获取成功",user);
        }else{
            return Result.fail("20002","用户未登录",user);
        }

    }

    /*
        获取验证码（操作台输出验证码）
     */
    @PostMapping("send")
    public Result send(@RequestBody UserForm userForm, HttpSession session){
        String tel = userForm.getUserTel();
        if(StringUtils.isEmpty(tel)){
            return Result.fail("30000","电话号码不能为空");
        }
        String captcha = RandomUtil.randomCode(6);

        smsService.send(tel,captcha);

        session.setAttribute("captcha",captcha);

        return Result.success("20027","验证码返回");
    }
    /*
        登录
        获取阿里云短信验证码
     */
    @GetMapping("/message")
    public  Result aliyun(String userTel,HttpSession session){
        String code = redisTemplate.opsForValue().get(userTel);
        if (!StringUtils.isEmpty(code)){
            return Result.success("80001","已存在，未过期");
        }
        //生成动态验证码并存入redis中
        code = UUID.randomUUID().toString().substring(0,4);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        //存入session
        session.setAttribute("code",code);
        boolean isSend = iUserService.send(userTel,"SMS_201718019",param);
        if (isSend){
            redisTemplate.opsForValue().set(userTel,code,5, TimeUnit.SECONDS);
            return Result.success("80005","发送成功");
        }else{
            return Result.fail("80004","发送失败");
        }
    }
    /*
        测试
        获取验证码
     */
    @GetMapping("/dx")
    public Result dx(String tel,HttpSession session){
      String  code = UUID.randomUUID().toString().substring(0,4);
        session.setAttribute("code",code);
        return Result.success("1","获取验证码",code);
    }


}

